package dao;

import dao.base.BaseDao;
import model.Meeting;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class MeetingDao extends BaseDao<Meeting> {

    private JdbcTemplate jdbcTemplate;

    public MeetingDao(Class aClass) {
        super(Meeting.class);
    }

    public List<Meeting> findPage(String title, Integer status, int startIndex, Integer pageSize) {
        try {
            jdbcTemplate = getJdbcTemplate();
            if(status == null){
                return jdbcTemplate.query("select * from meeting where title like ?" +
                        " order by publish_date desc limit ?,? ",
                        new BeanPropertyRowMapper<>(Meeting.class), "%"+title+"%", startIndex, pageSize);
            }else {
                return jdbcTemplate.query("select * from meeting where title like ? and status=? " +
                        "order by publish_date desc limit ?,?",
                        new BeanPropertyRowMapper<>(Meeting.class), "%"+title+"%", status, startIndex, pageSize);
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据会议标题和会议状态查询记录数
     * @param title
     * @param status
     * @return Integer
     */
    public Integer countByTitleAndStatus(String title, Integer status){
        try{
            if (status==null){
                return jdbcTemplate.queryForObject("select count(1) from meeting where title like ?",
                        Integer.class, "%"+title+"%");
            }else{
                return jdbcTemplate.queryForObject("select count(1) from meeting where title like ? and status=?",
                        Integer.class, "%"+title+"%", status);
            }
        }catch (Exception e){
            return null;
        }
    }

    public Integer findMeetingCountByMeetingId(Integer id) {
        try{
            return getJdbcTemplate().queryForObject("select count(1) from meeting_join where c_id = ?", Integer.class, id);
        }catch (Exception e){
            return null;
        }
    }

    public Integer checkJoin(Integer uId, Integer id) {
        try{
            return getJdbcTemplate().queryForObject("select count(1) from meeting_join where u_id = ? and c_id = ?;",
                    Integer.class, uId, id);
        }catch (Exception e){
            return null;
        }
    }

    public void unJoinMeeting(Integer uId, Integer id) {
        try{
            getJdbcTemplate().update("delete from meeting_join where u_id = ? and c_ id = ?", uId, id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void joinMeeting(Integer uId, Integer id) {
        try{
            getJdbcTemplate().update("insert into meeting_join value(?,?)", uId, id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
